//
//  CodebaseAlicloudSDK.m
//  CodebaseAlicloudSDK
//
//  Created by Theo Chen on 2020/2/18.
//

#import "MirrorLame.h"

@implementation MirrorLame

- (void)coverPCMFile:(NSString *)sourceFilePath toMP3Path:(NSString *)mp3FilePath withConfig: (LameConfig)config
        andCallback:(CallbackHandler)callback {
    NSLog(@"开始转换");
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        @try {
            int read, write;
            
            FILE *pcm = fopen([sourceFilePath cStringUsingEncoding:1],
                              "rb"); // source 被转换的音频文件位置
            fseek(pcm, 4 * 1024, SEEK_CUR); // skip file header
            FILE *mp3 = fopen([mp3FilePath cStringUsingEncoding:1],
                              "wb"); // output 输出生成的Mp3文件位置
            
            const int PCM_SIZE = 8192;
            const int MP3_SIZE = 8192;
            short int pcm_buffer[PCM_SIZE * config.channelsCount];
            unsigned char mp3_buffer[MP3_SIZE];
            
            lame_t lame = lame_init();
            lame_set_in_samplerate(lame, config.sampleRateKey);
            lame_set_VBR(lame, vbr_default);
            lame_set_quality(lame, config.quality);
            lame_init_params(lame);
            
            do {
                read = fread(pcm_buffer, config.channelsCount * sizeof(short int), PCM_SIZE, pcm);

                if (read == 0){
                    write = lame_encode_flush(lame, mp3_buffer, MP3_SIZE);
                } else if (config.channelsCount == 1) {
                    write = lame_encode_buffer(lame, pcm_buffer, NULL, read,
                    mp3_buffer, MP3_SIZE);
                } else {
                    write = lame_encode_buffer_interleaved(lame, pcm_buffer, read,
                                                        mp3_buffer, MP3_SIZE);
                }
                
                fwrite(mp3_buffer, write, 1, mp3);
                
            } while (read != 0);
            
            lame_close(lame);
            fclose(mp3);
            fclose(pcm);
            NSLog(@"MP3生成成功");
            dispatch_async(dispatch_get_main_queue(), ^{
                callback(mp3FilePath);
            });
        } @catch (NSException *exception) {
            NSLog(@"生成MP3失败%@", [exception description]);
            dispatch_async(dispatch_get_main_queue(), ^{
                callback(NULL);
            });
        } @finally {
            
        }
    });
}
@end
